<?php

/**
 *  It manages database of Story table
 * @property int $story_id primary key
 * @property int $user_id 
 * @property int $text 
 * @property string $text
 * @property int $time_created
 * @author tuancasi
 */
class Story extends CActiveRecord {

    const TOTAL_RECORD = 8;

    public $userName;

    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{story}}';
    }

    public function relations() {
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_id')
	);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	return array(
	    array('text', 'required', 'on' => 'insert, update'),
	    array('text', 'length', 'max' => 1000),
	    array('story_id, user_id, time_created, userName', 'safe')
	);
    }

    /**
     * search in frontend
     */
    public function search() {
	$criteria = new CDbCriteria();
	$criteria->compare('text', $this->text, TRUE);
	$criteria->addCondition('user_id=' . user()->id);
	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'story_id' => CSort::SORT_DESC
		)
	    )
	));
    }

    /**
     * search in frontend
     */
    public function searchBackend() {
	$criteria = new CDbCriteria();
	$criteria->with = 'user';
	$criteria->compare('user.username', $this->userName, TRUE);
	$criteria->compare('text', $this->text, TRUE);
	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'story_id' => CSort::SORT_DESC
		)
	    )
	));
    }

}

